import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { addTab, timeLimit } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import PageHeader from '@/components/PageHeader';

import {
  Table,
  Card,
  Row,
  Col,
  Input,
  Button,
  Cascader,
  DatePicker,
  Modal,
  Descriptions,
} from 'antd';
import { QuestionCircleFilled } from '@ant-design/icons';

import RechargeInfo from './components/RechargeInfo';

import '@ant-design/compatible/assets/index.css';

const { pathname } = window.location;
const { RangePicker } = DatePicker;
const { Item } = Form;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  datalist: any;
  INITINFO: any;
  screen: string;
}

interface TableListState {
  current: number;
  pageSize: number | undefined;
  searchValues: any;
  visible: boolean;
  formValues: {
    fcs_id: number,
    fcs_name: string;
  },
  tipsVisbile: boolean;
  rowId: number;
}

function mapStateToProps(state: any) {
  const {
    withdrawalMoney: { datalist },
    common: { INITINFO },
    global: { screen },
    loading,
  } = state;

  return {
    datalist,
    INITINFO,
    screen,
    loading: loading.effects['withdrawalMoney/fetch'],
  };
}

@connect(mapStateToProps)
class TableList extends React.Component<TableListProps, TableListState> {
  columns = [
    {
      title: '上级合作商',
      dataIndex: 'parent_name',
    },
    {
      title: '合作商',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '总收入(元)',
      dataIndex: 'total_income',
    },
    {
      title: '线下收入(元)',
      dataIndex: 'total_offline_income',
    },
    {
      title: '已提现金额(元)',
      dataIndex: 'total_withdraw',
    },
    {
      title: '账户余额(元)',
      dataIndex: 'income',
    },
    {
      title: '操作',
      render: (text: any, record: any) => (
        <div>
          <span
            onClick={this.handleChangeModal.bind(this, true, record)}
            className="operLink"
          >
            提现
          </span>
        </div>
      ),
    },
  ];

  state: TableListState = {
    current: 1,
    pageSize: 20,
    searchValues: {},
    visible: false,
    formValues: {
      fcs_id: 0,
      fcs_name: '',
    },
    rowId: 0,
    tipsVisbile: false,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...searchValues } = query;

    return {
      ...state,
      searchValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchAction('common/fetchAddressList');

    const { datalist } = this.props;
    if (datalist?.list?.length) return;

    this.fetchRechargeList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, current, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchRechargeList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const {
      searchValues: { start_time, end_time, ...others },
    } = this.state;

    if (start_time) {
      others.start_end_time = [moment(start_time), moment(end_time)];
    } else {
      others.start_end_time = [moment(moment().subtract(15, 'days').format('YYYY-MM-DD'))];
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  }

  // 获取数据
  fetchRechargeList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'withdrawalMoney/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const {
      searchValues: { areaCodes, start_time, ...params },
      current,
      pageSize,
    } = this.state;

    if (areaCodes && areaCodes.length) {
      [params['org1.area_code'], params['org2.area_code'], params['org3.area_code']] = areaCodes;
    }
    params.pageNum = current;
    params.numPerPage = pageSize;
    params.start_time = start_time || moment().subtract(15, 'days').format('YYYY-MM-DD');

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.start_end_time && fieldsValue.start_end_time.length) {
        fieldsValue.start_time = moment(fieldsValue.start_end_time[0]).format('YYYY-MM-DD');
        fieldsValue.end_time = moment(fieldsValue.start_end_time[1]).format('YYYY-MM-DD');
      } else {
        fieldsValue.start_time = '';
        fieldsValue.end_time = '';
      }
      delete fieldsValue.start_end_time;

      const query = { page: 1, ...fieldsValue };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '合作商提现',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '合作商提现',
      url: pathname,
      isTopMenu: true,
    });
  };

  /**
   * 查看提现记录
   */
  handleRecords = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '提现记录',
      url: '/partner/withdrawalMoney/list/records',
    });
  }

  /**
   * 查看入账明细
   */
  handleBooked = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '入账明细',
      url: '/partner/withdrawalMoney/list/booked',
    });
  }

  /**
   * 提现
   */
  handleChangeModal = (visible: boolean, record?: any) => {
    if (visible) {
      const { fcs_id, name: fcs_name } = record;
      const params = {
        fcs_id,
        fcs_name,
        pay_way: 1,
      };

      const { dispatch } = this.props;
      dispatch({
        type: 'withdrawalMoney/payWay',
        payload: params,
      }).then((res: any) => {
        if (res.code === 0) {
          this.setState({
            visible,
            formValues: { fcs_id, fcs_name },
          });
        }
      });
    } else {
      this.setState({ visible });
    }
  }


  // 分页
  onSelectChange = (page: number, psize: number | undefined) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, page, psize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '合作商提现',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  fetchAction = (typeName: string, params = {}) => {
    const { searchValues } = this.state;
    const { dispatch } = this.props;
    if (typeName === 'alipay') {
      params = {
        searchValues,
        ...params,
      };
    }
    const type = typeName.indexOf('common') >= 0
      ? typeName : `withdrawalMoney/${typeName}`;
    dispatch({
      type,
      payload: params,
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  renderSearchFormElem = () => {
    const {
      form: { getFieldDecorator },
      INITINFO: { addressList },
    } = this.props;

    return (
      <Form hideRequiredMark onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={12} sm={24}>
            <Item label="起止时间" colon={false}>
              {getFieldDecorator('start_end_time')(
                <RangePicker
                  placeholder={['开始时间', '截止时间']}
                  style={{ width: '100%' }}
                  format="YYYY/MM/DD"
                  disabledDate={timeLimit}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="　省市区" colon={false}>
              {getFieldDecorator('areaCodes')(
                <Cascader changeOnSelect options={addressList} placeholder="请选择" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="商户名称" colon={false}>
              {getFieldDecorator('fcs_name')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Item label="手机号码" colon={false}>
              {getFieldDecorator('phone')(
                <Input allowClear type="number" placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={18} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>

    );
  }

  render() {
    const {
      current,
      pageSize,
      visible,
      formValues,
      tipsVisbile,
    } = this.state;

    const {
      datalist,
      loading,
    } = this.props;

    const pagination: object = datalist
      ? {
        total: datalist ? datalist.count : 0,
        pageSize,
        current,
        onChange: this.onSelectChange,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${datalist.count || 0}条数据`,
        onShowSizeChange: this.onSelectChange,
        showQuickJumper: true,
      }
      : {};

    const dataSource = (datalist && datalist.list) || [];

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleRecords}
            >
              提现记录
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleBooked}
            >
              入账明细
            </Button>
            <span
              className="operLink"
              style={{ float: 'right', color: '#52c41a' }}
              onClick={() => this.setState({ tipsVisbile: true })}
            >
              <QuestionCircleFilled style={{ marginRight: 8 }} />
              页面帮助
            </span>
          </div>
          <Table
            rowKey="id"
            loading={loading}
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <RechargeInfo
          visible={visible}
          formValues={formValues}
          fetchAction={this.fetchAction.bind(this)}
          changeModal={this.handleChangeModal.bind(this)}
        />

        <Modal
          title="页面帮助"
          visible={tipsVisbile}
          width={600}
          footer={null}
          onCancel={() => this.setState({ tipsVisbile: false })}
        >
          <div style={{ overflowY: 'auto' }}>
            <Descriptions column={1} size="small" bordered>
              <Descriptions.Item label="总收入">
                起止时间-结束时间内各种业务的总入账金额。包含线上揽件收入、线上派件收入、线上寄存收入、柜体现金的总收入
              </Descriptions.Item>
              <Descriptions.Item label="线下收入">
                起止时间-结束时间内所有的现金收入，之前版本码枪揽件产生负数的收入本期计算后补充到线下收入中，以后线下收入只有柜体现金收入，如柜体无现金功能，将不会产生线下收入
              </Descriptions.Item>
              <Descriptions.Item label="已提现金额">
                起止时间-结束时间内已提现成功的金额
              </Descriptions.Item>
              <Descriptions.Item label="账户余额">
                当前全部可提现余额。包含揽件、派件、寄存业务扣除服务费后的实际到账金额
              </Descriptions.Item>
            </Descriptions>
          </div>
        </Modal>
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
